package org.xwalk.core;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;

/**
 * This class allows developers to determine whether any XWalkView used in the application has stored
 * data entered into text fields and to clear any such stored data for all XWalkView in thes application.
 */

public class XWalkViewDatabase   {



    private static XWalkCoreWrapper coreWrapper;


    /**
     * Gets whether there is any saved data for web forms.
     *
     * @return whether there is any saved data for web forms
     * @see #clearFormData
     * @since 8.0
     */
    public static boolean hasFormData() {
        reflectionInit();
        try {
            return (Boolean) hasFormDataMethod.invoke();
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                throw new RuntimeException("Crosswalk's APIs are not ready yet");
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        return false;
    }

    private static ReflectMethod hasFormDataMethod = new ReflectMethod(null, "hasFormData");

    /**
     * Clears any saved data for web forms.
     *
     * @see #hasFormData
     * @since 8.0
     */
    public static void clearFormData() {
        reflectionInit();
        try {
            clearFormDataMethod.invoke();
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                clearFormDataMethod.setArguments();
                XWalkCoreWrapper.reserveReflectMethod(clearFormDataMethod);
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        
    }

    private static ReflectMethod clearFormDataMethod = new ReflectMethod(null, "clearFormData");


    static void reflectionInit() {
        if (coreWrapper != null) return;

        XWalkCoreWrapper.initEmbeddedMode();

        coreWrapper = XWalkCoreWrapper.getInstance();
        if (coreWrapper == null) {
            XWalkCoreWrapper.reserveReflectClass(XWalkViewDatabase.class);
            return;
        }

        Class<?> bridgeClass = coreWrapper.getBridgeClass("XWalkViewDatabaseBridge");

        hasFormDataMethod.init(null, bridgeClass, "hasFormData");
        clearFormDataMethod.init(null, bridgeClass, "clearFormData");
    }
  
}
